Skip to content

Fix importlib mode shadowing an installed package with a namespace package (#13257)#14709

Open
vismaytiwari wants to merge 1 commit into
pytest-dev:mainfrom
vismaytiwari:fix/importlib-shadow-installed-package-13257
Open

Fix importlib mode shadowing an installed package with a namespace package (#13257)#14709
vismaytiwari wants to merge 1 commit into
pytest-dev:mainfrom
vismaytiwari:fix/importlib-shadow-installed-package-13257

Conversation

@vismaytiwari

Copy link
Copy Markdown
Contributor

Fixes #13257.

Since #12752, --import-mode=importlib eagerly builds a test module's parent packages. When a test file's rootdir-relative path reuses the name of an installed package — e.g. mypkg/tests/test_foo.py living next to the real mypkg/mypkg package — pytest bound the outer directory as a namespace package under that name in sys.modules, shadowing the real installed package. from mypkg import version in the tests then failed with:

ImportError: cannot import name 'version' from 'mypkg' (unknown location)

This regressed in 8.3.4 (the reporter bisected it to 3d3ec57 / #12752, which fixed #12592).

Fix

_import_module_using_spec now defers to the real package when the directory it would otherwise turn into a namespace parent already contains an importable package of the same fully-qualified name (i.e. the real package lives inside that directory).

The "inside that directory" check is what keeps this narrow: a test directory named after a standard-library module (math, time, …) has its real module living elsewhere, so it is still shadowed by a namespace package as before — test_importlib_same_name_as_stl and the #12592 behavior are unchanged.

Testing

…ckage (pytest-dev#13257)

Since pytest-dev#12752, importing a test module under `--import-mode=importlib` eagerly
builds its parent packages. When a test file's rootdir-relative path reuses the
name of an installed package -- for example `mypkg/tests/test_foo.py` living
next to the real `mypkg/mypkg` package -- pytest bound the outer directory as a
namespace package under that name in `sys.modules`, shadowing the real package.
`from mypkg import version` in the tests then failed with
"cannot import name ... (unknown location)".

Defer to the real package when a directory that would become a namespace parent
already contains an importable package of the same name (the real package lives
inside that directory). A test directory named after a standard-library module
lives elsewhere and is still shadowed by a namespace package, so
test_importlib_same_name_as_stl and the pytest-dev#12592 behavior are preserved.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided (automation) changelog entry is part of PR

Projects

None yet

1 participant